package com.nice.service;

import com.alibaba.fastjson.JSON;
import com.nice.common.CacheUtils;
import com.nice.dao.ObjectDao;
import com.nice.entity.PriceSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * 这里主要完成一些系统参数初始化
 */
@Service
public class InitParam {
    @Autowired
    public ObjectDao objectDao;

    public void init_Cache_From_TABLE_SELECT_INDEX_NAME(){
//        Map<String, String> map = (Map<String, String>) objectDao.selectIndexNameMap();
//        System.out.println("从文本库，初始化自选牌价到内存="+JSON.toJSONString(map));
//        if (map == null) {
//            System.out.println("无自选牌价数据");
//        }else{
//            CacheUtils.selectIndexName.putAll((Map<String, String>)objectDao.selectIndexNameMap());
//        }
    }

    public void refushPrice() {
        ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
        timer.scheduleWithFixedDelay(() -> {
            //lamba表达式写一个线程
            try {
                for (int i = 1; i < 15; i++) {
                    int max = 5;
                    int min = 1;
                    Random random = new Random();
                    int s = random.nextInt(max) % (max - min + 1) + min;
                    PriceSchema priceSchema = new PriceSchema();
                    String indexName = "index" + i;
                    priceSchema.setIndexName("index" + i);
                    priceSchema.setAsk(String.valueOf(i * s - 1));
                    priceSchema.setBid(String.valueOf(i * s + 1));

                    //随机更新
                    s = random.nextInt(max) % (max - min + 1) + min;
                    if (s == 1 || CacheUtils.priceInfo.keySet().size() < 15) {
                        CacheUtils.priceInfo.put(indexName, priceSchema);
                    }
                }
            } catch (Exception e) {
                timer.shutdownNow();
                e.getMessage();
            }
        }, 0, 3, TimeUnit.SECONDS);
    }

}

